﻿using UnityEngine;
using System.Collections;
using UnityEditor;


public class Camera2DFollow : MonoBehaviour
{
    [Tooltip("跟踪目标")]
    public Transform target;
    [Tooltip("跟随速度")]
    public float followSpeed = 5.0f;
    [Tooltip("偏移")]
    public Vector2 offset = Vector2.zero;
    [Tooltip("是否跟踪Y轴")]
    public bool followY = false;


    private Vector2 relativeToTarget;
    private Vector3 oriPosition;

    private bool startFollow = false;

    void Awake()
    {
        relativeToTarget = transform.position - target.position;
        oriPosition = transform.position;
    }

    void OnEnable()
    {
        GameManager.Instance.OverEvents += StopFollow;
        GameManager.Instance.ResetEvents += Reset;
    }

    void OnDisable()
    {
        GameManager.Instance.OverEvents -= StopFollow;
        GameManager.Instance.ResetEvents -= Reset;
    }

    void FixedUpdate()
    {
        if (startFollow)
        {
            if (followY)
            {
                transform.position = Vector3.Lerp(transform.position,
                    new Vector3(target.position.x + relativeToTarget.x + offset.x,
                        target.position.y + relativeToTarget.y + offset.y, transform.position.z),
                    followSpeed * Time.deltaTime);
            }
            else
            {
                transform.position = Vector3.Lerp(transform.position,
                    new Vector3(target.position.x + relativeToTarget.x + offset.x,
                        transform.position.y, transform.position.z),
                    followSpeed * Time.deltaTime);
            }
        }

    }

    public void StopFollow()
    {
        startFollow = false;
    }

    public void Reset()
    {
        transform.position = oriPosition;
        startFollow = true;
    }
}
